package org.bambrikii.kbManager.kb2.managers;

import org.bambrikii.kbManager.kb2.dao.IArtefactAsTextDAO;
import org.bambrikii.kbManager.kb2.managers.query5.And;
import org.bambrikii.kbManager.kb2.managers.query5.ICriteria;
import org.bambrikii.kbManager.kb2.managers.query5.Kind;
import org.bambrikii.kbManager.kb2.managers.query5.Like;
import org.bambrikii.kbManager.kb2.managers.query5.Source;
import org.bambrikii.kbManager.kb2.managers.query5.q.ParsedQuery;
import org.bambrikii.kbManager.kb2.managers.query5.q.QueryBuilder;
import org.bambrikii.kbManager.kb2.model.ArtefactAsText;
import org.bambrikii.site.base.model.Pager;
import org.bambrikii.site.base.pagers.dao.PagerBuilder;

class ArtefactAsTextPagerBuilder extends PagerBuilder<ArtefactAsText> {

	private final QueryBuilder builder = new QueryBuilder();
	private ParsedQuery query = null;

	ArtefactAsTextPagerBuilder(IArtefactAsTextDAO dao) {
		super(dao);
		// TODO: setCriteria(dao.getCriteria());
	}

	public void restrict(final String sourceKey) {
		synchronized (builder) {
			query = builder.getQuery(new Source(new Like(sourceKey)));
		}
	}

	public void restrict(final String sourceKey, final String kindKey) {
		synchronized (builder) {
			query = builder.getQuery(new Source(new And(new Like(sourceKey),
					new Kind(new Like(kindKey)))));
		}
	}

	@Override
	public Pager<ArtefactAsText> getPager(final int cols, final int rows,
			final String order, final int currPage) {
		final Pager<ArtefactAsText> pager = new Pager<ArtefactAsText>(cols,
				rows, currPage);
		final IArtefactAsTextDAO dao2 = (IArtefactAsTextDAO) getDao();
		synchronized (builder) {
			pager.setRecords(dao2.getListFromQuery(query.getListQuery(),
					pager.getStart(), pager.getLength()));
			pager.setTotalRecordsCount(dao2.getCountFromQuery(query
					.getCountQuery()));
		}
		return pager;
	}

	public Pager<ArtefactAsText> getPager(final ICriteria filter,
			final Integer currPage, final Integer cols, final Integer rows) {
		final Pager<ArtefactAsText> pager = new Pager<ArtefactAsText>(cols,
				rows, currPage);
		final IArtefactAsTextDAO dao2 = (IArtefactAsTextDAO) getDao();

		final QueryBuilder b = new QueryBuilder();
		final ParsedQuery q = b.getQuery(filter);
		pager.setRecords(dao2.getListFromQuery(q.getListQuery(),
				pager.getStart(), pager.getLength()));
		pager.setTotalRecordsCount(dao2.getCountFromQuery(q.getCountQuery()));
		return pager;
	}
}
